<template>
  <div id="app" style="width: 100%;height: 100px">
    <PlaybackControl ref="playbackControlRef" @clickTime="handleDblClick"></PlaybackControl>
  </div>
</template>


<script lang="ts" setup>
import PlaybackControl from './components/playback-control.vue'
import { useWebSocket } from '@vueuse/core';
import type { UseWebSocketReturn } from '@vueuse/core';

import { onMounted, onUnmounted, ref } from 'vue'

const playbackControlRef = ref<any>(null);
const channelNumber = ref(1);
const wsUrl = 'ws://192.168.1.6:22203'
let wsConnection: UseWebSocketReturn<any> | null = null;
let start = performance.now();

// 处理 WebSocket 接收到的消息
const handleWebSocketMessage = async (_ws: WebSocket, event: MessageEvent) => {
  try {
    // 尝试将接收到的数据解析为 JSON 格式
    const data = JSON.parse(event.data);
    if (playbackControlRef.value) {
      playbackControlRef.value.setTimeRange({start: data.start_ts_utc, end: data.end_ts_utc})
      let timeRangeList: any[] = []
      data.valid_fragment.map((range: {start_ts:number, end_ts:number}) => {
        timeRangeList.push({start: range.start_ts, end: range.end_ts})
      })
      playbackControlRef.value.setTimeRangeList(timeRangeList)
      playbackControlRef.value.setTimeMark(data.start_ts_utc + 100000);
    }
  } catch (error) {
    console.error('Error parsing message:', error);
  }
};

const handleDblClick = (time: number) => {
  console.info(`跳转时间点：${time}`);
}

onMounted(() => {
  wsConnection = useWebSocket(wsUrl, {
    autoReconnect: true,
    onMessage: handleWebSocketMessage,
    onError: (error: any) => {
      console.error('SenserChannel WebSocket error:', error);
    },
    onConnected: () => {
      console.info('SenserChannel WebSocket connected');
      wsConnection?.send(JSON.stringify({
        messageType: 'gettimerange',
        channelnumber: channelNumber.value,
      }));
    },
  });
})

onUnmounted(() => {
  // 在组件销毁前清除定时器
  wsConnection?.close();
});

</script>
<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #0b0e11;
  margin-top: 60px;
}
</style>
